﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;


namespace OneMG.Phoenix.Kernel.Helper
{
    public class FileHelper
    {
        private static object _lock = new object();

        #region 检测扩展名的有效性
        /// <summary>
        /// 检测扩展名的有效性
        /// </summary>
        /// <param name="AllowExt">允许的文件名扩展名</param>
        /// <param name="sExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        public static bool CheckValidExt(string AllowExt, string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == "." + sExt)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        /// <summary>
        /// 检测扩展名的有效性
        /// </summary>
        /// <param name="AllowExt">允许的文件名扩展名</param>
        /// <param name="sExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        public static bool CheckValidExtNew(string AllowExt, string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == sExt)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
        #endregion

        #region 取得文件的扩展名
        /// <summary>
        /// 取得文件的扩展名
        /// </summary>
        /// <param name="sFilePath"></param>
        /// <returns></returns>
        public static string GetFileExt(string sFilePath)
        {
            string sExt = "";
            if (sFilePath != "")
            {
                sFilePath.Substring(sFilePath.LastIndexOf(".")).ToLower();
            }
            return sExt;
        }
        #endregion

        #region 创建文件夹 判断文件夹是否存在
        /// <summary>
        /// 创建文件夹,调用此方法可省去判断文件夹是否存在的判断,每次对
        /// 文件夹操作前调用一下此方法即可
        /// </summary>
        /// <param name="serverPhysicalPath"></param>
        public static void CreateFolderIfNotExist(string serverPhysicalPath)
        {
            if (!Directory.Exists(serverPhysicalPath))
            {
                Directory.CreateDirectory(serverPhysicalPath);
            }
        }
        #endregion

        #region 取得一个文件的后缀名
        /// <summary>
        /// 取得一个文件的后缀名
        /// </summary>
        /// <param name="clientPhysicalPath">文件名或文件路径</param>
        /// <returns></returns>
        public static string GetSuffixOfFile(string clientPhysicalPath)
        {
            int intSuffixPos = clientPhysicalPath.LastIndexOf(".");
            string strSuffix = clientPhysicalPath.Substring(intSuffixPos + 1).ToLower().Trim();
            return strSuffix;
        }
        #endregion

        #region 在文件上传时获取根据上传自动建立目录标记所建立的目录名称
        /// <summary>
        /// 主要用在文件上传时获取根据上传自动建立目录标记所建立的目录名称
        /// </summary>
        /// <param name="sign">上传自动建立目录标记．0不建目录，1年目录，2年月目录，3年月日目录</param>
        /// <returns>返回根据上传自动建立目录标记所建立的目录名称</returns>
        /// <permission cref="System.Security.PermissionSet">public</permission>
        public static string GetDirectoryByTime(System.String sign)
        {
            string path = System.String.Empty;
            if (sign.Equals("0"))
            {
                //不建立目录
            }
            else if (sign.Equals("1"))
            {
                //以年为标志建立目录
                path = DateTime.Now.Year.ToString();
            }
            else if (sign.Equals("2"))
            {
                //以年-月为标志建立目录
                path = System.String.Concat(DateTime.Now.Year.ToString(), "-", DateTime.Now.Month.ToString("00"));
            }
            else if (sign.Equals("3"))
            {
                //以年-月-日为标志建立目录
                path = System.String.Concat(DateTime.Now.Year.ToString(), "-", DateTime.Now.Month.ToString("00"), "-", DateTime.Now.Day.ToString("00"));
            }
            return path;
        }
        /// <summary>
        /// 图片调整上传的路径及文件名称
        /// </summary>
        /// <param name="serverPhysicalPath">要上传服务地址</param>
        /// <param name="type">图片类型</param>
        /// <param name="fileName">输出文件名</param>
        /// <returns>返回所建立的文件路径</returns>
        public static string GetDirectoryFileName(string serverPhysicalPath, DirctoryImg type, out string fileName)
        {
            // 暂时通过加锁来解决文件名重复问题
            lock (_lock)
            {
                fileName = RandomHelper.GetSystemID(23);
            }

            string oneDirectory = fileName.Substring(20, 3);//一级目录
            string twoDirectory = fileName.Substring(17, 3);//二级目录
            string strPath = null;
            switch (type)
            {
                case DirctoryImg.SupplyImg:
                    strPath = string.Format(@"Product/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.BuyImg:
                    strPath = string.Format(@"Product/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.SetThemeImg:
                    strPath = string.Format(@"SetTheme/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.AdvertisementImg:
                    strPath = string.Format(@"Advertisement/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.CompanyLogoImg:
                    strPath = string.Format(@"CompanyLogo/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.CertImg:
                    strPath = string.Format(@"CertImg/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.ProductImg:
                    strPath = string.Format(@"AlbumImg/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.OtherImg:
                    strPath = string.Format(@"upload/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.LoanImg:
                    strPath = string.Format(@"LoanImg/{0}/{1}/", oneDirectory, twoDirectory);
                    break;
                case DirctoryImg.LoanDocument:
                    strPath = string.Format(@"LoanDocument/{0}/{1}/", oneDirectory, twoDirectory);
                    break;

            }

            FileInfo fi = new FileInfo(serverPhysicalPath + strPath);
            if (!fi.Exists)
            {
                DirectoryInfo di = new DirectoryInfo(serverPhysicalPath + strPath);
                di.Create();
            }

            return strPath;
        }
        #endregion

        #region 文件读写操作
        private static Encoding defaultEncoding = Encoding.UTF8;

        #region 读取文本文件
        /// <summary>
        /// ReadTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <returns>文本内容</returns>
        public static string ReadTextFile(string fileName)
        {
            string str = null;
            try
            {
                str = ReadTextFile(fileName, defaultEncoding);
            }
            catch (Exception ex)
            {
                //记录日志
                //Logger.Error(ex);
                WriteTextFile(fileName, "");
                str = ReadTextFile(fileName, defaultEncoding);
            }
            return str;
        }

        /// <summary>
        /// ReadTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="encoding">编码</param>
        /// <returns>文本内容</returns>
        public static string ReadTextFile(string fileName, Encoding encoding)
        {
            string text;

            using (StreamReader sr = new StreamReader(fileName, encoding))
            {
                text = sr.ReadToEnd();
            }

            return text;
        }
        #endregion

        #region 写入文本文件
        /// <summary>
        /// WriteTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="text">文本内容</param>
        public static void WriteTextFile(string fileName, string text)
        {
            WriteTextFile(fileName, text, false, true, defaultEncoding);
        }

        /// <summary>
        /// WriteTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="text">文本内容</param>
        /// <param name="encoding">编码</param>	
        public static void WriteTextFile(string fileName, string text, Encoding encoding)
        {
            WriteTextFile(fileName, text, false, true, encoding);
        }

        /// <summary>
        /// WriteTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="text">文本内容</param>
        /// <param name="createDir">是否创建目录</param>		
        public static void WriteTextFile(string fileName, string text, bool createDir)
        {
            WriteTextFile(fileName, text, false, createDir, defaultEncoding);
        }

        /// <summary>
        /// WriteTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="text">文本内容</param>
        /// <param name="createDir">是否创建目录</param>
        /// <param name="encoding">编码</param>	
        public static void WriteTextFile(string fileName, string text, bool createDir, Encoding encoding)
        {
            WriteTextFile(fileName, text, false, createDir, encoding);
        }

        /// <summary>
        /// WriteTextFile
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="text">文本内容</param>
        /// <param name="append">是否添加到文本后面</param>
        /// <param name="createDir">是否创建目录</param>
        /// <param name="encoding">编码</param>
        public static void WriteTextFile(string fileName, string text, bool append, bool createDir, Encoding encoding)
        {
            if (createDir)
            {
                string dirName = Path.GetDirectoryName(fileName);

                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
            }

            using (StreamWriter sw = new StreamWriter(fileName, append, encoding))
            {
                sw.Write(text);
            }
        }
        #endregion

        #endregion

        #region 字节值
        /// <summary>
        /// 文件类型
        /// </summary>
        public enum FileType
        {
            /// <summary>
            /// 文本
            /// </summary>
            Txt = 1,

            /// <summary>
            /// Rar
            /// </summary>
            Rar = 2,

            /// <summary>
            /// Zip
            /// </summary>
            Zip = 4,

            /// <summary>
            /// Bmp
            /// </summary>
            Bmp = 8,

            /// <summary>
            /// Jpg
            /// </summary>
            Jpg = 16,

            /// <summary>
            /// Gif
            /// </summary>
            Gif = 32,

            /// <summary>
            /// Png
            /// </summary>
            Png = 64,

            /// <summary>
            /// Doc
            /// </summary>
            Doc = 128,

            /// <summary>
            /// Xls
            /// </summary>
            Xls = 256,

            /// <summary>
            /// Pdf
            /// </summary>
            Pdf = 512
        }
        #endregion

        #region
        public enum DirctoryImg
        {
            /// <summary>
            /// 发布供应信息产品图片
            /// </summary>
            SupplyImg = 1,
            /// <summary>
            /// 发布求购信息产品图片
            /// </summary>
            BuyImg = 2,
            /// <summary>
            /// 主题元素图片
            /// </summary>
            SetThemeImg = 3,
            /// <summary>
            /// 会员广告图片
            /// </summary>
            AdvertisementImg = 4,
            /// <summary>
            /// 公司Logo图片
            /// </summary>
            CompanyLogoImg = 5,
            /// <summary>
            /// 荣誉证书图片
            /// </summary>
            CertImg = 6,
            /// <summary>
            /// 产品相册图片
            /// </summary>
            ProductImg = 7,
            /// <summary>
            /// 产品相册图片
            /// </summary>
            OtherImg = 8,
            /// <summary>
            /// 融资申请产品
            /// </summary>
            LoanImg = 9,
            /// <summary>
            /// 资料
            /// </summary>
            LoanDocument = 10
        }
        #endregion
    }
}
